package com.wx.house.manager.api.permission.controller;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.wx.house.manager.api.permission.service.SysAdminRoleService;
import com.wx.house.manager.api.permission.service.SysRoleService;
import com.wx.house.manager.api.permission.text.SysAdminRolePame;
import com.wx.house.common.base.BaseController;
import com.wx.house.common.exception.BusinessException;
import com.wx.house.common.util.IDUtils;
import com.wx.house.common.util.JwtUtils;
import com.wx.house.core.pojo.base.Result;
import com.wx.house.core.pojo.po.SysAdminRole;
import com.wx.house.core.pojo.po.SysRole;

import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("SysAdminRole/")
@Api(value = "管理员角色模块", tags = "模块:管理员角色模块")
@Slf4j
public class SysAdminRoleController extends BaseController{
	@Resource
	private SysAdminRoleService sysAdminRoleService;
	@Resource
	private SysRoleService sysRoleService;
	
	@ApiOperation(value = "分配角色", notes = "分配角色")
	@PostMapping("addAdminRole/")
	public Result addAdminRole(@RequestBody @Validated SysAdminRolePame sysAdminRolePame, HttpServletRequest request) {
		try {
			String token = request.getHeader("authorization");
			//step1. 解析token
			Claims claims = JwtUtils.builder().token(token).build().claims();
			//step2. 从token获取参数,获取账号id
			String id = claims.get("id").toString();
			if(id.equals(sysAdminRolePame.getAdminId())) {
				return Result.error("自己不能给自己分配权限");
			}
			sysAdminRoleService.dateAdminRole(sysAdminRolePame.getAdminId());
			for (int i = 0; i < sysAdminRolePame.getRoleId().size(); i++) {
				SysAdminRole adminRole=SysAdminRole.builder()
						.id(IDUtils.genItemId(8)+"")
						.adminId(sysAdminRolePame.getAdminId())
						.roleId(sysAdminRolePame.getRoleId().get(i))
						.operation("李好")
						.operationTime(new Date())
						.build();
				sysAdminRoleService.addAdminRole(adminRole);	
			}
			return Result.success();
		} catch (Exception e) {
		  throw new BusinessException("分配角色失败");
		}
	}
	/***
	 * 查询用户角色
	 */
	@ApiOperation(value = "根据用户查询角色", notes = "根据用户查询角色")
	@GetMapping("SeleRoleTree/")
    public Result<List<SysRole>> getRoleTree(String adminId) {
		try {
			List<SysRole> baseLists= sysRoleService.AdminRole(adminId);
	        return Result.success(baseLists);
		} catch (Exception e) {
			 throw new BusinessException("查询失败");
		}
    }
}